//
//  ShopGoodViewController.m
//  BaseFrame
//
//  Created by 孟学浩 on 2017/5/18.
//  Copyright © 2017年 com.mxh. All rights reserved.
//

#import "ShopGoodViewController.h"
#import "ShopGoodCollectionViewCell.h"
#import "ShopGoodInfoViewController.h"
#import "PulldownView.h"

@interface ShopGoodViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>{
    NSString *cc_id;
}

@property (nonatomic,strong) UICollectionView *collectionView;
@property (nonatomic,strong) NSMutableArray *dataArray;

@property (nonatomic,strong) UIView *titleView;
@property (nonatomic,strong) UIButton *titleButton;

@property (nonatomic,strong) PulldownView *pulldownView;
Strong NSMutableArray *pulldownViewArray; /**<*/
Assign int pstart;

@end

//网络
@implementation ShopGoodViewController (NetWorking)

- (void)getEnterTheShopAdvertisingChartInterface{
    [self showprogressHUD];
    NSDictionary *parameters = @{@"id":[UserModel sharedInstanced].userId};
    [[AFAppDotNetAPIClient sharedClient] POST:@"LaundryMall/Store_Mobile/enterTheShopAdvertisingChartInterface.action" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        if ([responseObject[@"responseStatus"] isEqualToString:@"0"]) {
            [self.pulldownViewArray  removeAllObjects];
                for (int i = 0 ; i < [responseObject[@"obj1"] count]; i ++) {
                    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:responseObject[@"obj1"][i]];
                    if (![dic[@"cc_name"] isEqualToString:@" "]) {
                        [self.pulldownViewArray addObject:dic];
                    }
                }
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}

- (void)getData:(int)pstart{
    [self showprogressHUD];
    if ([[UserModel sharedInstanced].s_id isEqualToString:@""]) {
        [self hiddenProgressHUD];
        return;
    }
    NSDictionary *parameters = @{@"id":[UserModel sharedInstanced].s_id,
                                 @"pstart":[NSString stringWithFormat:@"%d",self.pstart],
                                 @"psize":@"20"};
    [[AFAppDotNetAPIClient sharedClient] POST:@"LaundryMall/Commodity/displayAllGoods.action" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        [self.collectionView.mj_header endRefreshing];
        [self.collectionView.mj_footer endRefreshing];
        if ([responseObject[@"responseStatus"] isEqualToString:@"0"]) {
            if (pstart == 0) {
                [self.dataArray removeAllObjects];
                self.pstart = 0;
            }
            self.pstart ++;
            [self.dataArray addObjectsFromArray:responseObject[@"obj"]];
            [self.collectionView reloadData];
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self.collectionView.mj_header endRefreshing];
        [self.collectionView.mj_footer endRefreshing];
        [self showError:error];
    }];
}

- (void)getDataCcid{
    [self showprogressHUD];
    NSDictionary *parameters = @{@"s_id":[UserModel sharedInstanced].s_id,
                                 @"cc_id":cc_id};
    [[AFAppDotNetAPIClient sharedClient] POST:@"LaundryMall/Commodity/viewCategoryItems.action" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        if ([responseObject[@"responseStatus"] isEqualToString:@"0"]) {
            [self.dataArray removeAllObjects];
            self.pstart = 1;
            [self.dataArray addObjectsFromArray:responseObject[@"obj"]];
            [self.collectionView reloadData];
            self.collectionView.mj_footer = nil;
        }else{
            [self.dataArray removeAllObjects];
            [self.collectionView reloadData];
            ShowMessage(responseObject[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}

@end

@implementation ShopGoodViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    self.navigationItem.title = @"商品列表";
    self.navigationItem.titleView = self.titleView;
    [self.titleView addSubview:self.titleButton];
    [self.view addSubview:self.collectionView];
    
    UIButton * rightButton = [[UIButton alloc]init];
    rightButton.size = CGSizeMake(40, 20);
    [rightButton setTitle:@"添加" forState:UIControlStateNormal];
    [rightButton.titleLabel setFont:DEF_FontSize_12];
    rightButton.layer.masksToBounds = YES;
    rightButton.layer.cornerRadius = 3;
    rightButton.layer.borderColor = [[UIColor whiteColor] CGColor];
    rightButton.layer.borderWidth = 1;
    [rightButton addTarget:self action:@selector(rightBarButtonItemClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    //设置barbutton
    self.navigationItem.rightBarButtonItem = rightItem;
    [self getData:0];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self getEnterTheShopAdvertisingChartInterface];
}

#pragma mark - click

- (void)rightBarButtonItemClick{
    if (!cc_id) {
        ShowMessage(@"请选择分类");
        return;
    }
    ShopGoodInfoViewController *vc = [ShopGoodInfoViewController new];
    vc.hidesBottomBarWhenPushed = YES;
    vc.type = ShopGoodsType_Add;
    vc.ccId = cc_id;
    [self.navigationController pushViewController:vc animated:YES];
}
// 点击标题按钮选择分类
- (void)chooseShopType{
    [self.pulldownView showInSuperView:self.view];
}
#pragma mark - UICollectionViewDelegate,UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    ShopGoodCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([ShopGoodCollectionViewCell class]) forIndexPath:indexPath];
    cell.model = self.dataArray[indexPath.row];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    ShopGoodInfoViewController *vc = [ShopGoodInfoViewController new];
    vc.hidesBottomBarWhenPushed = YES;
    vc.type = ShopGoodsType_Change;
    vc.c_id = self.dataArray[indexPath.row][@"c_id"];
    [self.navigationController pushViewController:vc animated:YES];
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    UICollectionReusableView *view = nil;
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:NSStringFromClass([UICollectionReusableView class]) forIndexPath:indexPath];
        view.backgroundColor = [UIColor whiteColor];
//        [view addSubview:self.imgView];
    }
    return view;
}


#pragma mark - set & get
- (UIView *)titleView{
    if(!_titleView){
        _titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 80/WIDTH_5S_SCALE, 25/WIDTH_5S_SCALE)];
        
        UIImageView *subscript = [[UIImageView alloc] initWithFrame:CGRectMake(70/WIDTH_5S_SCALE, 10/WIDTH_5S_SCALE, 10/WIDTH_5S_SCALE, 10/WIDTH_5S_SCALE)];
        subscript.image = [UIImage imageNamed:@"三角下标"];
//        subscript.backgroundColor = [UIColor redColor];
        [_titleView addSubview:subscript];
        
    }
    return _titleView;
}

- (UIButton *)titleButton{
    if(!_titleButton){
        _titleButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 70/WIDTH_5S_SCALE, 25/WIDTH_5S_SCALE)];
        _titleButton.titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:15];
        [_titleButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_titleButton setTitle:@"请选择分类" forState:UIControlStateNormal];
        [_titleButton addTarget:self action:@selector(chooseShopType) forControlEvents:UIControlEventTouchUpInside];
    }
    return _titleButton;
}

- (UICollectionView *)collectionView{
    if (!_collectionView) {
        
        int offset = 5;
        
        UICollectionViewFlowLayout *layout = [UICollectionViewFlowLayout new];
        layout.minimumLineSpacing = offset;
        layout.minimumInteritemSpacing = offset;
        layout.sectionInset = UIEdgeInsetsMake(offset, offset, offset, offset);
        layout.itemSize = CGSizeMake((SCREEN_WIDTH - 20)/3., (SCREEN_WIDTH - 20)/3.);
//        layout.headerReferenceSize = CGSizeMake(SCREEN_WIDTH, 160/WIDTH_5S_SCALE);

        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64-49) collectionViewLayout:layout];
        _collectionView.backgroundColor = getColor(@"f1f2f6");
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [self getData:0];
        }];
        _collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            [self getData:self.pstart];
        }];
        
        [_collectionView registerClass:[ShopGoodCollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([ShopGoodCollectionViewCell class])];
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:NSStringFromClass([UICollectionReusableView class])];
    }
    return _collectionView;
}

- (PulldownView *)pulldownView{
    if(!_pulldownView){
        _pulldownView = [[PulldownView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - 49)];
        __weak __typeof(self)weakSelf = self;
        _pulldownView.dataArray = self.pulldownViewArray;
        _pulldownView.clickedAtIndexBlock = ^(NSInteger index) {
            NSLog(@"点击了第%ld行",index);
            cc_id = weakSelf.pulldownView.dataArray[index][@"cc_id"];
            NSString *str = weakSelf.pulldownView.dataArray[index][@"cc_name"];
            [weakSelf.titleButton setTitle:[NSString stringWithFormat:@"%@",str] forState:UIControlStateNormal];
            [weakSelf getDataCcid];
        };
    }
    return _pulldownView;
}
#pragma mark - data

- (NSMutableArray *)pulldownViewArray{
    if (!_pulldownViewArray) {
        _pulldownViewArray = @[].mutableCopy;
    }
    return _pulldownViewArray;
}

- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray  = @[
                        ].mutableCopy;
    }
    return _dataArray;
}


@end
